package com.liuwa.social.weixin.push;

import com.alibaba.fastjson.JSONObject;
import com.liuwa.social.http.WeixinHttpClient;
import com.liuwa.social.weixin.utils.WeixinUtils;
import com.liuwa.social.weixin.vo.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 订阅通知任务
 * @author rubekid
 *
 * 2018年6月21日 下午7:04:50
 */
public class SubscribeTask implements Runnable{
	
	
	public final static Logger LOGGER = LoggerFactory.getLogger(SubscribeTask.class);
	
	private static final String PUSH_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";

	
	/**
	 * 应用ID
	 */
	private String appId;
	
	/**
	 * 应用秘钥
	 */
	private String appSecret;
	
	/**
	 * 模板
	 */
	private SubscribeTemplate template; 
	
   
	
	public SubscribeTask(String appId, String appSecret){
		this.appId = appId;
		this.appSecret = appSecret;
	}

	
	public SubscribeTask(String appId, String appSecret, SubscribeTemplate template){
		this.appId = appId;
		this.appSecret = appSecret;
		this.template = template;
	}

	
	@Override
	public void run() {
		try {
			AccessToken accessToken = WeixinUtils.getAccessToken(appId, appSecret);
			String url = String.format(PUSH_URL, accessToken.getAccessToken());
			String content = WeixinHttpClient.post(url, (JSONObject)(JSONObject.toJSON(template)));
			LOGGER.info("\n=============================\nNOTIFY RESULT :{}", content);

		} catch (RuntimeException ex) {
			LOGGER.error(ex.getMessage(), ex);
		}
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getAppSecret() {
		return appSecret;
	}

	public void setAppSecret(String appSecret) {
		this.appSecret = appSecret;
	}

	public SubscribeTemplate getTemplate() {
		return template;
	}

	public void setTemplate(SubscribeTemplate template) {
		this.template = template;
	}

}
